package com.xsm.activitygroup;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpClientConnection;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.xsm.activitygroup.R;
import com.xsm.activitygroup.Welcome.MyHandler;
import com.xsm.internet.ConnectUrl;
import com.xsm.internet.PostMessage;
import com.xsm.view.Mydialog;

public class UpdateActivity extends Activity{

	String packageName="",versionname="";
	  SharedPreferences sharedPreferences;
	  int versioncode;
	  Activity context;
	  TextView result,nversion;
	  String resultString="";
	  DownHandler downHandler;
	  long rfilelength=0;
	  ProgressBar bar;
	  TextView pTextView;
	  static int STATE=0;//1下载中0暂停-1初始化
	  DownLoad loadThread;
	  long startindex=0;
	long  filelength;
	Button load;
	JSONArray resultArray;	
 
	
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	   super.onCreate(savedInstanceState);
	   setContentView(R.layout.update);
	   context=this;
	   downHandler=new DownHandler();
	   sharedPreferences=getSharedPreferences("XSM", 0);
	   packageName=sharedPreferences.getString("packageName", "");
	   versioncode=Integer.parseInt(sharedPreferences.getString("versioncode",""));
	   versionname=sharedPreferences.getString("versionname", "");
	   result=(TextView)findViewById(R.id.result);
	   nversion=(TextView)findViewById(R.id.nversion);
	   try {
		resultArray=new JSONArray(getIntent().getExtras().getString("updatetext"));
		JSONObject object=resultArray.getJSONObject(0);
		String text=object.get("updatetext").toString();
		String s[]=text.split("-");
		if(s.length>1){
		String showtext="";
		for(int i=1;i<s.length;i++){
		showtext=showtext+"-"+s[i]+"\n";	
		}
		result.setText(showtext);
		}
	    nversion.setText("最新版本\tV"+resultArray.getJSONObject(1).get("versionname").toString());
		
	  } catch (JSONException e) {
		e.printStackTrace();
	  }
	   
	   
	   bar=(ProgressBar)findViewById(R.id.progress);
	   load=(Button)findViewById(R.id.load);
	   load.setText("暂停");	
	   load.getBackground().setAlpha(150);
	   pTextView=(TextView)findViewById(R.id.progresstext);
		loadThread=new DownLoad();
		loadThread.start();
		
}
	
	public void Load(View view){
	if(startindex==filelength&&startindex!=0){
		String fileName = Environment.getExternalStorageDirectory() + "/XSM/xsm.apk";
		Intent intent1 = new Intent(Intent.ACTION_VIEW);
		intent1.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
		startActivity(intent1);		
	 }else {
			if(STATE==1){
			   STATE=0;
				load.setText("开始");
				}
			else {
				loadThread=new DownLoad();
				loadThread.start();
			    load.setText("暂停");	
			
			}
		}
	}
	

	

	
	class DownHandler extends Handler{
public void handleMessage(Message msg) {
	if(msg.what==-2){
		STATE=0;
		Toast.makeText(context, "内存不足", Toast.LENGTH_LONG).show();
	}
	else if(msg.what==-1){
		Toast.makeText(context, "连接失败,请重新点击开始", Toast.LENGTH_LONG).show();
		STATE=0;
		load.setText("开始");
	 }else{
		int pro=Integer.parseInt(msg.obj+"");
		bar.setProgress(pro);
		pTextView.setText(pro+"%");
		if(pro==100){
		load.setText("安装");
		String fileName = Environment.getExternalStorageDirectory() + "/XSM/xsm.apk";
		Intent intent1 = new Intent(Intent.ACTION_VIEW);
		intent1.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
		startActivity(intent1);	
	}

}
		

}
	}
	
	
	
class DownLoad extends Thread{
public void run() {
	if(STATE==1)
	return;
	STATE=1;
String urlString= ConnectUrl.uString+"/ShujiService/Apk/xsm.apk";	
String path=Environment.getExternalStorageDirectory()+"/XSM/";
File file=new File(path);
if(!file.exists()){
	file.mkdirs();
}
String filename="xsm.apk";
try {
	URL url2=new URL(urlString);
	HttpURLConnection connection2=(HttpURLConnection)url2.openConnection();
	connection2.setRequestMethod("GET");
	connection2.setConnectTimeout(5000);
	int code2=connection2.getResponseCode();
	if(code2==200||code2==206){
	filelength=connection2.getContentLength();	
	if(filelength>getSdcardFreeSize()){
		Message msg=downHandler.obtainMessage();
		msg.what=-2;
		downHandler.sendMessage(msg);
		return;
	}
	}
	
	URL url=new URL(urlString);
	HttpURLConnection connection=(HttpURLConnection)url.openConnection();
	connection.setRequestMethod("GET");
	connection.setRequestProperty("Range","bytes="+startindex+"-"+filelength);
	connection.setConnectTimeout(5000);
	int code=connection.getResponseCode();
	InputStream inputStream=connection.getInputStream();
	if(code==200||code==206){
RandomAccessFile accessFile=new RandomAccessFile(path+filename,"rw");
accessFile.seek(startindex);
int len=0;
byte b[]=new byte[1024];
while (STATE==1){
	if((len=inputStream.read(b))==-1){
      STATE=0;
		break;
      }
	else {
		rfilelength+=len;
		startindex=rfilelength;
		int progress=(int)((rfilelength*100)/filelength);
		Message dmsg=downHandler.obtainMessage();
		dmsg.obj=progress;
		downHandler.sendMessage(dmsg);
		accessFile.write(b,0,len);	
	}
}
inputStream.close();
accessFile.close();
	}else {
	STATE=0;	
	Message msg=downHandler.obtainMessage();
	msg.what=-1;
	downHandler.sendMessage(msg);
	}
} catch (Exception e) {
	STATE=0;
	Message dmsg=downHandler.obtainMessage();
	dmsg.what=-1;
	downHandler.sendMessage(dmsg);
}
}
}
	
	public void Back(View view){
		final Mydialog dMydialog=new Mydialog(context, "退出将会取消更新,是否继续?");
		dMydialog.settitle("提示");
		dMydialog.setEnsurelistener(new OnClickListener() {
			public void onClick(View arg0) {
			if(loadThread.isAlive()){
			STATE=0;
			}
			dMydialog.dissmissDialog();
			finish();
			}
		});
		dMydialog.showDialog();
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(keyCode==event.KEYCODE_BACK){
			final Mydialog dMydialog=new Mydialog(context, "退出将会取消更新,是否继续?");
			dMydialog.settitle("提示");
			dMydialog.setEnsurelistener(new OnClickListener() {
				public void onClick(View arg0) {
				if(loadThread.isAlive()){
				STATE=0;
				}
				dMydialog.dissmissDialog();
				finish();
				}
			});
			dMydialog.showDialog();
		}
		return true;
	}
	
	
	public long getSdcardFreeSize(){
		File path = Environment.getExternalStorageDirectory();   
		  StatFs sf = new StatFs(path.getPath()); 
		  long blockSize = sf.getBlockSize();   
		  long freeBlocks = sf.getAvailableBlocks();  
		     //返回SD卡空闲大小  
		     //return freeBlocks * blockSize;  //单位Byte  
		     //return (freeBlocks * blockSize)/1024;   //单位KB  
		return (freeBlocks * blockSize); //单位b  
	}
	
	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}
	@Override
	protected void onPause() {
		MobclickAgent.onResume(this);
		super.onPause();
	}
}
